package com.ldk.admin.controller;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.enums.PlatformUserType;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * A.4.4、网约车平台公司服务机构信息
 * @author xiangwl
 * 2018年8月9日
 * com.ldk.admin.controller
 * CompanyserviceController
 */
@Controller
@RequestMapping("/baseinfo")
public class CompanyserviceController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "companyservice";
    /**
     * 模块名称
     */
    private final String module = "服务机构信息";
    @Autowired
    private ICompanyserviceService companyserviceService;

    @RequestMapping("/companyservice/list")
    public ModelAndView edit(ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module+"管理", "/baseinfo/"+route+"/list", "", "");
        } else {
            setLinks(map, "", "", module+"管理", "/baseinfo/"+route+"/list", "添加"+module, "/baseinfo/"+route+"/add");
        }

        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/baseinfo/"+route+"/list");
    }

    @ResponseBody
    @RequestMapping("/companyservice/getList")
    public LigerUIGridResult<Companyservice> getList(@RequestParam(value="page",required=false,defaultValue="1") int page,
                                                 @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
                                                 @RequestParam(value="ServiceName",required=false,defaultValue="") String ServiceName,
                                                 HttpServletRequest request)
    {
        int limit = pageSize;
        int offset = (page -1) * pageSize;

        Companyservice query = new Companyservice();
        if(!StringUtils.isBlank(ServiceName)){
            query.setServiceName(ServiceName);
        }

        CustomPageable pageable = new CustomPageable(offset, limit);

        Page<Companyservice> result = companyserviceService.selectPageList("", query, pageable);

        LigerUIGridResult<Companyservice> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @RequestMapping("/companyservice/add")
    public ModelAndView add(ModelMap map,HttpServletRequest request,
                            HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        setLinks(map, module+"管理", "/baseinfo/"+route+"/list", "添加"+module, "/baseinfo/"+route+"/add", "", "");
        setForm(map, "/baseinfo/"+route+"/insert", null);
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        Companyservice model = new Companyservice();

        return new ModelAndView("/baseinfo/"+route+"/info","model",model);
    }

    @RequestMapping("/companyservice/edit/{id}")
    public ModelAndView edit(@PathVariable long id, ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);
        Companyservice query = new Companyservice();
        query.setId(id);

        Companyservice model = companyserviceService.selectOne("", query);
        if(model == null){
            return new ModelAndView("redirect:/baseinfo/"+route+"/list");
        }
        setLinks(map, module+"管理", "/baseinfo/"+route+"/list", "编辑"+module, "/baseinfo/"+route+"/edit/"+id, "", "");
        setForm(map, "/baseinfo/"+route+"/update", null);
        map.addAttribute("route", route);
        map.addAttribute("module", module);

        return new ModelAndView("/baseinfo/"+route+"/info","model", model);
    }

    @RequestMapping("/companyservice/insert")
    public ModelAndView insert(@ModelAttribute("model") Companyservice model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);

        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        Boolean success = false;
        try{
            model.setUpdateTime(SystemUtil.getCurDateLong());
            model.setUpdateTime2(model.getUpdateTime());

            Companyservice query = new Companyservice();
            query.setCompanyId(model.getCompanyId());
            query.setServiceName(model.getServiceName());

            System.out.print("insert CompanyId="+model.getCompanyId()+"\r\n");
            System.out.print("insert ServiceName="+model.getServiceName()+"\r\n");
            System.out.print("insert ServiceNo="+model.getServiceNo()+"\r\n");
            System.out.print("insert DetailAddress="+model.getDetailAddress()+"\r\n");
            System.out.print("insert ResponsibleName="+model.getResponsibleName()+"\r\n");
            System.out.print("insert ResponsiblePhone="+model.getResponsiblePhone()+"\r\n");
            System.out.print("insert ManagerName="+model.getManagerName()+"\r\n");
            System.out.print("insert ContactPhone="+model.getContactPhone()+"\r\n");
            System.out.print("insert MailAddress="+model.getMailAddress()+"\r\n");
            System.out.print("insert CreateDate="+model.getCreateDate()+"\r\n");
            System.out.print("insert State="+model.getState()+"\r\n");
            System.out.print("insert Flag="+model.getFlag()+"\r\n");
            System.out.print("insert UpdateTime="+model.getUpdateTime()+"\r\n");
            System.out.print("insert UpdateTime2="+model.getUpdateTime2()+"\r\n");


            System.out.print("query CompanyId="+query.getCompanyId()+"\r\n");
            System.out.print("query ServiceName="+query.getServiceName()+"\r\n");


            long count = companyserviceService.selectCount("", query);
            if(count > 0){
                rst.AddError(String.format(" 服务机构:%s已经存在", model.getServiceName()));

                return new ModelAndView("redirect:/baseinfo/"+route+"/add");
            }

            this.insertOplog(request,module,"","","添加:"+query.getServiceName(),this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            model.setUpdateTime2(model.getUpdateTime());

            int row = companyserviceService.insert("", model);
            success = row > 0;

        }
        catch(Exception e){
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("添加" + module + "成功");
        } else {
            rst.AddError("添加" + module + "失败");
        }

        return new ModelAndView("redirect:/baseinfo/"+route+"/add");
    }

    @RequestMapping("/companyservice/update")
    public ModelAndView update(@ModelAttribute("model") Companyservice model,
                               RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
                               HttpServletResponse response)
    {
        //session是否过期
        this.isExpired(request,response);
        ResponseResult rst = new ResponseResult();
        redAttr.addAttribute("id", model.getId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        Boolean success = false;
        try{

            Companyservice query = new Companyservice();
            query.setCompanyId(model.getCompanyId());
            query.setAddress(model.getAddress());
            query.setServiceName(model.getServiceName());
            query.setServiceNo(model.getServiceNo());
            query.setDetailAddress(model.getDetailAddress());
            query.setResponsibleName(model.getResponsibleName());
            query.setResponsiblePhone(model.getResponsiblePhone());
            query.setManagerName(model.getManagerName());
            query.setManagerPhone(model.getManagerPhone());
            query.setContactPhone(model.getContactPhone());
            query.setMailAddress(model.getMailAddress());
            query.setCreateDate(model.getCreateDate());
            query.setState(model.getState());
            query.setFlag(1L);
            query.setUpdateTime(SystemUtil.getCurDateLong());

            Companyservice companyservice = companyserviceService.selectOne("", query);
            if(companyservice != null && !companyservice.getServiceName().equals(model.getServiceName())){
                rst.AddError(String.format("服务机构:%s已经存在", model.getServiceName()));

                return new ModelAndView("redirect:/baseinfo/"+route+"/edit/{id}");
            }

            this.insertOplog(request,module,"","","修改:"+query.getServiceName(),this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            //logger.error("companyservice.update.id="+model.getId()+",ServiceName"+model.getServiceName());

            int row = companyserviceService.updateByKey("", model);
            success = row > 0;

        }
        catch(Exception e){
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("编辑" + module + "成功");
        } else {
            rst.AddError("编辑" + module + "失败");
        }

        return new ModelAndView("redirect:/baseinfo/"+route+"/edit/{id}");
    }

    /**
     * 浏览
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/companyservice/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map,HttpServletRequest request,
                             HttpServletResponse response){
        //session是否过期
        this.isExpired(request,response);

        setViewMode(map, ViewMode.View);
        Companyservice query = new Companyservice();
        query.setId(id);
        Companyservice model = companyserviceService.selectOne("", query);

        map.addAttribute("module", module);

        return new ModelAndView("/baseinfo/"+route+"/info","model", model);
    }

    @ResponseBody
    @RequestMapping("/companyservice/remove/{id}")
    public ResponseResult remove(@PathVariable long id, HttpServletRequest request){

        ResponseResult rst = new ResponseResult();
        if(id < 1)
        {
            rst.AddError("删除"+module+"错误");
            return rst;
        }
        Boolean successed = false;
        try{
            Companyservice query = new Companyservice();
            query.setId(id);
            int row = companyserviceService.deleteByKey("", query);
            successed = row > 0;
        }
        catch(Exception e){
            logger.error(e.getMessage());
        }
        if(successed){
            rst.AddOk("删除"+module+"成功");
        }
        else{
            rst.AddError("删除"+module+"失败");
        }

        return rst;
    }
}
